import effects from './effects';
import listeners from './listeners';
import { produce } from 'immer';
import { set, omit, values } from 'lodash';
import { registerForm, unRegisterForm, validateFormGetErrors } from '@/pages/Myantd/Form/FormUtils';

export default {
  namespace: 'forms',
  state: {
    BtnConfig: {},
    formsValue: {},
    forms: {},
  },
  effects: {
    ...effects,
    ...listeners,
  },
  reducers: {
    registerForm(state: any, { payload }: any) {
      const { form, formId } = payload;
      const nextState = produce(state, (draftState: any) => {
        const oldforms = state?.forms || {}
        const result = registerForm({ oldforms, form, formId })
        console.log('registerForm', result);
        set(draftState, 'forms', result);
      });
      return { ...nextState };

    },
    unRegisterForm(state: any, { payload }: any) {
      const { form, formId } = payload;
      const nextState = produce(state, (draftState: any) => {
        const oldforms = state?.forms
        const result = unRegisterForm({ oldforms, form, formId })
        console.log('unRegisterForm', result);

        set(draftState, `forms`, result);
      });
      return { ...nextState };

    },
    // validateForm(state: any, { payload }: any) {
    //   const forms = state?.forms
    //   const errors = validateFormGetErrors({
    //     forms: values(forms)
    //   })

    //   const nextState = produce(state, (draftState: any) => {
    //     set(draftState, `errors`, errors);
    //   });
    //   return {
    //     ...nextState
    //   };
    // },

    setFormFields(state: any, { payload }: any) {
      const nextState = produce(state, (draftState: any) => {
        console.log('setFormFields', payload);
        set(draftState, `formsValue.${Object.keys(payload)[0]}`, Object.values(payload)[0]);
      });
      return { ...nextState };
    },

    setBtnConfig(state: any, { payload }: any) {
      const nextState = produce(state, (draftState: any) => {
        set(draftState, 'BtnConfig', payload);
      });
      return { ...nextState };
    },
  },
  subscriptions: {},
};
